package webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 处理输入输出流
 * 
 * @ClassName: Processor
 * @Description:
 * @Copyright: Copyright (c) 2016
 * @Company: FFCS
 * @author Zhengliang
 * @date 2016年4月8日 上午10:57:49
 */
public class Processor extends Thread {
	private final static String WEB_ROOT = "D:\\Workspaces\\git\\webserver\\htdocs\\";
	
	// test 
	
	private Socket socket;
	private InputStream is;
	private PrintStream ps;
	
	private String inte = "test";

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			// 获取socket里的输入流
			is = socket.getInputStream();
			ps = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String filename = parse(is);
		sendFile(filename);
	}

	public String parse(InputStream is) {
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String filename = "";
		String[] contArr = null;
		try {
			// 获取头部第一行
			String httpMessage = br.readLine();
			if(httpMessage != null){
				contArr = httpMessage.split(" ");
			}

			if (contArr == null || contArr.length != 3) {
				this.sendErrorMessage(400, "客户请求错误");
				return null;
			}

			// 协议状态
			System.out.println("code : " + contArr[0]);
			// 请求文件名称
			filename = contArr[1];
			System.out.println("filename : " + filename);
			// 协议版本号
			System.out.println("http version : " + contArr[2]);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 发送错误信息
	 * 
	 * @Title: sendErrorMessage
	 * @Description:
	 * @param errorCode
	 * @param errorMessage
	 *            void
	 * @throws
	 */
	public void sendErrorMessage(int errorCode, String errorMessage) {
		ps.println("HTTP/1.0 " + errorCode + " " + errorMessage);
		ps.println("content-type : text/html");
		ps.println();
		ps.println("<html><head><title>Error Message</title>");
		ps.println("</head><body>");
		ps.println("<h1>ErrorCode : " + errorCode + ", ErrorMessage : " + errorMessage + "</h1>");
		ps.println("</body></html>");
		ps.flush();
		ps.close();
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 请求服务器文件
	 * 
	 * @Title: sendFile
	 * @Description:
	 * @param filename
	 *            void
	 * @throws
	 */
	public void sendFile(String filename) {
		File file = new File(Processor.WEB_ROOT + filename);
		if (!file.exists()) {
			this.sendErrorMessage(404, "客户访问资源不存在");
			return;
		}

		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int) file.length()];
			in.read(content);
			ps.println("HTTP/1.0 200 返回文件是干什么的");
			ps.println("content-length : " + file.length());
			ps.println();
			ps.write(content);
			ps.flush();
			ps.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
